﻿using BestHTTP;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VoiceRecognitionIndexed : MonoBehaviour
{
    List<HTTPRequest> requests = new List<HTTPRequest>();
    int offset = 0;
    List<int> segStart = new List<int>();
    bool recording = false;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void VoiceRecognitionStart()
    {
        requests.Clear();
        offset = 0;
        segStart.Clear();
        segStart.Add(0);
        recording = true;
    }

    public void VoiceRecognitionStop()
    {
        recording = false;
    }

    public void OnSilence()
    {
        segStart.Add(requests.Count + offset);
    }

    public void OnVoiceRecordBytes(byte[] bytes)
    {
        if (!recording)
            return;

        byte[] bytes2 = new byte[bytes.Length];
        Buffer.BlockCopy(bytes, 0, bytes2, 0, bytes.Length);

        var request = new HTTPRequest(new Uri("https://ilab.chu-jiao.com:8069/Interface/speech"), HTTPMethods.Post, onFinished);
        request.AddBinaryData("file", bytes2, "file.wav");
        request.AddField("rate", "8000");
        request.AddField("format", "pcm");
        request.Send();
        requests.Add(request);
    }

    private void onFinished(HTTPRequest originalRequest, HTTPResponse response)
    {
        int ind = 0;
        for (; ind < requests.Count; ind++)
        {
            if (requests[ind] == originalRequest)
                break;
        }
        ind += offset;

        if (requests.Count > 20)
        {
            requests.RemoveRange(0, 10);
            offset += 10;
        }

        if (response != null)
        {
            if (response.IsSuccess == false)
            {
                print("VoiceRecognitionIndexed, recognizing failed.");
                return;
            }

            string[] strs = parseResult(response.DataAsText);
            Dictionary<string, string> results = new Dictionary<string, string>();
            results["index"] = ind.ToString();
            int segInd = 0;
            for(int i=0;i<segStart.Count;i++)
            {
                if(ind<segStart[i])
                    break;
                segInd = i;
            }
            results["seg"] = segInd.ToString();
            results["result"] = strs[1];
            if (strs[0] == "success.")
                SendMessage("OnVoiceRecognitionIndexed_Result", results);
        }
        else
        {
            print("VoiceRecognitionIndexed, no response, please check network.");
            SendMessage("OnVoiceRecognitionIndexed_NoResponse");
        }
    }

    string[] parseResult(string str)
    {
//        print("parsing:" + str);
        if (str[0] == '{')
            str = str.Substring(1);
        if (str[str.Length - 1] == '}')
            str = str.Substring(0, str.Length - 1);
        string[] strs = str.Split(',');

        string[] ss = new string[2];
        for (int i = 0; i < strs.Length; i++)
        {
            string[] tmp = strs[i].Split(':');
            if (tmp[0] == "\"err_msg\"")
                ss[0] = tmp[1].Substring(1, tmp[1].Length - 2);
            if (tmp[0] == "\"result\"")
                ss[1] = tmp[1].Substring(2, tmp[1].Length - 4);
        }

        return ss;
    }
}
